<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>车辆模拟运行监控系统</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"
    integrity="sha512-SfTiTlX6kk+qitfevl/7LibUOeJWlt9rbyDn92a1DqWOw9vWG2MFoays0sgObmWazO5BQPiFucnnEAjpAB+/Sw=="
    crossorigin="anonymous" referrerpolicy="no-referrer" />
  <!-- 主CDN链接 -->
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.5.0/dist/chart.umd.min.js"></script>

  <!-- 配置Tailwind自定义颜色 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#00a3ff',
            secondary: '#00ffdd',
            accent: '#ff3d71',
            dark: '#050e2d',
            darker: '#03091e',
            'dark-card': '#0a193a',
            'dark-border': '#162955'
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .glow {
        box-shadow: 0 0 10px rgba(0, 163, 255, 0.5);
      }
      .glow-accent {
        box-shadow: 0 0 10px rgba(255, 61, 113, 0.7);
      }
      .text-shadow {
        text-shadow: 0 0 8px rgba(0, 163, 255, 0.7);
      }
      .bg-grid {
        background-image: 
          linear-gradient(rgba(22, 41, 85, 0.1) 1px, transparent 1px),
          linear-gradient(90deg, rgba(22, 41, 85, 0.1) 1px, transparent 1px);
        background-size: 20px 20px;
      }
      .scrollbar-hide::-webkit-scrollbar {
        display: none;
      }
      .gradient-border {
        position: relative;
        border: double 1px transparent;
        background-image: linear-gradient(#0a193a, #0a193a), 
                          linear-gradient(to right, #00a3ff, #00ffdd);
        background-origin: border-box;
        background-clip: padding-box, border-box;
      }
    }
    .amap-logo{
       display: none;
       opacity:0 !important;
       }
       .amap-copyright {
           opacity:0;
       }
  </style>
</head>

<body class="bg-dark text-gray-200 min-h-screen bg-grid overflow-x-hidden">
  <!-- 顶部导航栏 -->
  <header class="bg-darker border-b border-dark-border px-6 py-3 flex justify-between items-center">
    <div class="flex items-center">
      <i class="fa fa-car text-primary text-2xl mr-3"></i>
      <h1 class="text-xl md:text-2xl font-bold text-white">智能车辆模拟运行监控系统</h1>
    </div>
    <div class="flex items-center space-x-4">
      <div class="text-sm text-gray-400">
        <span id="current-date">2023-06-15</span> <span id="current-time">14:35:22</span>
      </div>
      <a href="index.html"
        class="bg-dark-card px-3 py-1 rounded text-primary text-sm cursor-pointer hover:bg-dark-border transition-colors duration-300">
        <i class="fa fa-home mr-1"></i> 首页
      </a>
      <div id="configurationBtn"
        class="bg-dark-card px-3 py-1 rounded text-primary text-sm cursor-pointer hover:bg-dark-border transition-colors duration-300">
        <i class="fa fa-sliders mr-1"></i> 运行参数
      </div>
      <div id="addSimulationBtn"
        class="bg-dark-card px-3 py-1 rounded text-accent text-sm cursor-pointer hover:bg-dark-border transition-colors duration-300">
        <i class="fa fa-plus-circle mr-1"></i> 添加模拟
      </div>
      <div id="toggleSimulationBtn"
        class="bg-dark-card px-3 py-1 rounded text-secondary text-sm cursor-pointer hover:bg-dark-border transition-colors duration-300">
        <i class="fa fa-list-alt mr-1"></i> 模拟记录
      </div>
    </div>
  </header>

  <!-- 模拟记录侧边栏 -->
  <div id="simulationSidebar"
    class="fixed top-18 left-0 w-80 h-[calc(100vh-72px)] bg-darker border-r border-dark-border z-40 transform -translate-x-full transition-transform duration-300 ease-in-out overflow-y-auto scrollbar-hide">
    <div class="p-4 border-b border-dark-border">
      <div class="flex justify-between items-center">
        <h3 class="font-semibold text-white">模拟记录列表</h3>
        <button id="closeSidebarBtn" class="text-gray-400 hover:text-white transition-colors">
          <i class="fa fa-times"></i>
        </button>
      </div>
      <div class="mt-2 text-xs text-gray-400">
        显示最近的模拟运行记录
      </div>
    </div>
    <div id="simulationRecordsContainer" class="p-3 space-y-3">
      <!-- 模拟记录将通过JavaScript动态生成 -->
      <div class="flex justify-center items-center h-40 text-gray-400">
        <span>加载模拟记录中...</span>
      </div>
    </div>
  </div>

  <!-- 侧边栏遮罩 -->
  <div id="sidebarOverlay"
    class="fixed inset-0 bg-black/50 backdrop-blur-sm z-30 hidden transition-opacity duration-300 ease-in-out"></div>

  <main class="container mx-auto px-4 py-3 grid grid-cols-1 lg:grid-cols-12 gap-4 h-[calc(100vh-72px)]">
    <!-- 左侧数据面板 -->
    <section class="lg:col-span-3 space-y-4 flex flex-col">
      <!-- 总车辆数和运行车辆数 -->
      <div class="bg-dark-card rounded-lg p-4 border border-dark-border glow">
        <div class="flex justify-between items-start mb-2">
          <h3 class="font-semibold text-gray-300 text-sm">车辆统计</h3>
          <span id="runningRatio" class="text-xs bg-primary/20 text-primary px-2 py-1 rounded-full">
            运行占比: 49.6%
          </span>
        </div>
        <div class="grid grid-cols-2 gap-2">
          <div>
            <div class="text-xs text-gray-400 mb-1">总车辆数</div>
            <div class="text-2xl font-bold text-white text-center">
              1<span class="text-primary">4</span>3
            </div>
          </div>
          <div>
            <div class="text-xs text-gray-400 mb-1">运行车辆数</div>
            <div class="text-2xl font-bold text-white text-center">
              <span class="text-primary">7</span>1
            </div>
          </div>
        </div>
      </div>

      <!-- 车辆类型分布 -->
      <div class="bg-dark-card rounded-lg p-4 border border-dark-border">
        <div class="flex justify-between items-center mb-3">
          <h3 class="font-semibold text-gray-300 text-sm">车辆类型分布</h3>
          <i class="fa fa-chevron-right text-primary/70 text-xs"></i>
        </div>
        <div class="h-[240px]">
          <canvas id="vehicleTypeChart"></canvas>
        </div>
      </div>

      <!-- 系统运行指标 -->
      <div class="bg-dark-card rounded-lg p-4 border border-dark-border">
        <div class="flex justify-between items-center mb-3">
          <h3 class="font-semibold text-gray-300 text-sm">系统运行指标</h3>
          <span class="text-xs text-gray-400">运行数据</span>
        </div>
        <div class="space-y-2">
          <div class="flex justify-between items-center">
            <div class="flex items-center">
              <i class="fa fa-cogs text-primary mr-2"></i>
              <span>资源利用率</span>
            </div>
            <span id="resourceUtil" class="font-medium">78.5%</span>
          </div>
          <div class="flex justify-between items-center">
            <div class="flex items-center">
              <i class="fa fa-money text-green-400 mr-2"></i>
              <span>总成本</span>
            </div>
            <span id="totalCost" class="font-medium">¥26,438</span>
          </div>
          <div class="flex justify-between items-center">
            <div class="flex items-center">
              <i class="fa fa-clock-o text-yellow-400 mr-2"></i>
              <span>总时间</span>
            </div>
            <span id="totalTime" class="font-medium">8,640 分钟</span>
          </div>
          <div class="flex justify-between items-center">
            <div class="flex items-center">
              <i class="fa fa-road text-secondary mr-2"></i>
              <span>总距离</span>
            </div>
            <span id="totalDistance" class="font-medium">18,742 km</span>
          </div>
          <div class="flex justify-between items-center">
            <div class="flex items-center">
              <i class="fa fa-leaf text-green-500 mr-2"></i>
              <span>碳排放</span>
            </div>
            <span id="carbonEmissions" class="font-medium">42.3 吨</span>
          </div>
          <div class="flex justify-between items-center">
            <div class="flex items-center">
              <i class="fa fa-smile-o text-purple-400 mr-2"></i>
              <span>满意度</span>
            </div>
            <span id="satisfaction" class="font-medium">92.7%</span>
          </div>
        </div>
      </div>
    </section>

    <!-- 中间地图区域 -->
    <section class="lg:col-span-6 space-y-4">
      <!-- 成都地图 -->
      <div class="bg-dark-card rounded-lg p-4 border border-dark-border h-[400px] relative overflow-hidden">
        <div class="flex justify-between items-center mb-4">
          <div class="flex space-x-2">
            <button class="text-xs bg-primary/20 text-primary px-2 py-1 rounded hover:bg-primary/30 transition"
              id="refreshMap">
              <i class="fa fa-refresh mr-1"></i> 刷新
            </button>
            <button class="text-xs bg-dark px-2 py-1 rounded hover:bg-darker transition" id="filterMap">
              <i class="fa fa-filter mr-1"></i> 筛选
            </button>
          </div>
        </div>

        <!-- 高德地图容器 -->
        <div id="container" class="w-full h-[350px] relative bg-darker rounded-lg overflow-hidden"></div>
      </div>

      <!-- 运行车辆成本明细 -->
      <div class="bg-dark-card rounded-lg p-4 border border-dark-border flex-1">
        <div class="flex justify-between items-center mb-2">
          <h3 class="font-semibold text-gray-300 text-sm">运行车辆成本明细</h3>
          <i class="fa fa-chevron-right text-primary/70 text-xs"></i>
        </div>
        <div class="h-[240px]">
          <canvas id="areaDensityChart"></canvas>
        </div>
      </div>
    </section>

    <!-- 右侧数据面板 -->
    <section class="lg:col-span-3 space-y-4">
      <!-- 车辆状态统计 -->
      <div class="bg-dark-card rounded-lg p-4 border border-dark-border">
        <div class="flex justify-between items-center mb-3">
          <h3 class="font-semibold text-gray-300 text-sm">车辆状态统计</h3>
          <i class="fa fa-chevron-right text-primary/70 text-xs"></i>
        </div>
        <div class="h-[200px]">
          <canvas id="vehicleStatusChart"></canvas>
        </div>
      </div>

      <!-- 异常事件监控 -->
      <div class="bg-dark-card rounded-lg p-4 border border-dark-border">
        <div class="flex justify-between items-center mb-2">
          <h3 class="font-semibold text-gray-300 text-sm">异常事件</h3>
          <span id="anomalyCount" class="text-xs bg-accent/20 text-accent px-2 py-1 rounded-full">
            34 起
          </span>
        </div>
        <div id="anomalyEventsContainer" class="space-y-2 max-h-[130px] overflow-y-auto scrollbar-hide">
          <div class="bg-darker p-3 rounded-lg border-l-2 border-accent">
            <div class="flex justify-between items-start mb-1">
              <span class="text-sm font-medium">交通事故</span>
            </div>
            <div class="flex justify-between text-xs">
              <span>影响车辆: 12辆</span>
              <span class="text-accent">严重</span>
            </div>
          </div>

          <div class="bg-darker p-3 rounded-lg border-l-2 border-yellow-400">
            <div class="flex justify-between items-start mb-1">
              <span class="text-sm font-medium">交通拥堵</span>
            </div>
            <div class="flex justify-between text-xs">
              <span>影响车辆: 42辆</span>
              <span class="text-yellow-400">中等</span>
            </div>
          </div>

          <div class="bg-darker p-3 rounded-lg border-l-2 border-yellow-400">
            <div class="flex justify-between items-start mb-1">
              <span class="text-sm font-medium">车辆故障</span>
            </div>
            <div class="flex justify-between text-xs">
              <span>影响车辆: 1辆</span>
              <span class="text-yellow-400">轻微</span>
            </div>
          </div>

          <div class="bg-darker p-3 rounded-lg border-l-2 border-accent">
            <div class="flex justify-between items-start mb-1">
              <span class="text-sm font-medium">道路施工</span>
            </div>
            <div class="flex justify-between text-xs">
              <span>影响车辆: 28辆</span>
              <span class="text-accent">严重</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 系统性能指标 -->
      <div class="bg-dark-card rounded-lg p-4 border border-dark-border">
        <div class="flex justify-between items-center mb-2">
          <h3 class="font-semibold text-gray-300 text-sm">系统性能指标</h3>
          <i class="fa fa-chevron-right text-primary/70 text-xs"></i>
        </div>
        <div class="h-[180px]">
          <canvas id="efficiencyChart"></canvas>
        </div>
      </div>
    </section>
  </main>

  <!-- 高德地图安全配置 -->
  <script type="text/javascript">
    window._AMapSecurityConfig = {
      securityJsCode: '8a6d78f268b9752750db254de21b27f1',
    };
  </script>
  <!-- 加载高德地图API -->
  <script src="https://webapi.amap.com/loader.js"></script>

  <script>
    // 显示当前真实时间并每秒更新
    function updateCurrentTime() {
      const now = new Date();

      // 格式化日期：YYYY-MM-DD
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const formattedDate = `${year}-${month}-${day}`;

      // 格式化时间：HH:MM:SS
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const seconds = String(now.getSeconds()).padStart(2, '0');
      const formattedTime = `${hours}:${minutes}:${seconds}`;

      // 更新DOM元素
      document.getElementById('current-date').textContent = formattedDate;
      document.getElementById('current-time').textContent = formattedTime;
    }

    // 初始更新时间
    updateCurrentTime();

    // 设置定时器，每秒更新一次时间
    setInterval(updateCurrentTime, 1000);

    // 初始化高德地图
    AMapLoader.load({
      key: "6fb521344f076267522e0112298656c5",
      version: "2.0",
      plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.MapType', 'AMap.Geocoder'],
      AMapUI: {
        version: '1.1',
        plugins: []
      },
      Loca: {
        version: '2.0.0'
      }
    }).then(() => {
      // 创建地图实例
      const map = new AMap.Map('container', {
        viewMode: '2D',
        zoom: 15,
        center: [104.100265, 30.675679],
        mapStyle: 'amap://styles/darkblue'
      });

      // 添加地图控件
      map.addControl(new AMap.ToolBar());
      map.addControl(new AMap.Scale());
      map.addControl(new AMap.MapType());


      // 刷新按钮事件
      document.getElementById('refreshMap').addEventListener('click', function () {
        map.refresh();
      });

      // 筛选按钮事件
      document.getElementById('filterMap').addEventListener('click', function () {
        alert('筛选功能将在后续版本中实现');
      });

      // 地图初始化完成后，如果全局变量中已有数据，则直接更新页面
      // 否则等待fetchAndDisplaySimulationRecords完成
      if (globalSimulationRecords) {
        fetchDataAndUpdatePage();
      }

      // 设置定时刷新数据 - 刷新时会先检查全局变量
      setInterval(() => {
        // 清空全局变量，强制重新获取数据
        globalSimulationRecords = null;
        // 先获取模拟记录（会更新全局变量）
        fetchAndDisplaySimulationRecords().then(() => {
          // 然后更新页面数据
          fetchDataAndUpdatePage();
        });
      }, 30000); // 每30秒刷新一次数据
    }).catch(e => {
      console.error('地图加载失败:', e);
      // 即使地图加载失败，也尝试加载和显示数据
      fetchDataAndUpdatePage();
      setInterval(fetchDataAndUpdatePage, 30000);
    });

    // 获取数据并更新页面的函数
    async function fetchDataAndUpdatePage() {
      try {
        // 先检查全局变量中是否已有数据
        if (globalSimulationRecords && globalSimulationRecords.length > 0) {
          // 使用全局变量中的第一个数据
          updatePageData(globalSimulationRecords[0]);
          initializeAllCharts(globalSimulationRecords[0]);
        } else {
          // 如果全局变量中没有数据，则从API获取
          const optimizationData = await fetchOptimizationData();
          updatePageData(optimizationData);
          initializeAllCharts(optimizationData);
        }
      } catch (error) {
        console.error('更新页面数据失败:', error);
      }
    }

    // 从后端API获取数据
    async function fetchOptimizationData() {
      try {
        // 先检查全局变量中是否已有数据
        if (globalSimulationRecords && globalSimulationRecords.length > 0) {
          return globalSimulationRecords[0];
        }
        
        // 如果全局变量中没有数据，则从API获取
        const response = await fetch('http://localhost:8080/VRP/optimization/list');
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        const data = await response.json();
        
        // 检查是否有可用数据，如果有则返回第一个optimization
        if (data && data.length > 0) {
          // 存储到全局变量供后续使用
          globalSimulationRecords = data;
          return data[0];
        }
        
        throw new Error('No optimization data available');
      } catch (error) {
        console.error('Error fetching optimization data:', error);
        // 返回模拟数据，以防API不可用
        return {
          optimizationName: "智慧物流实时监控",
          totalVehicleCount: 50,
          runningVehicleCount: 42,
          runningVehiclePercentage: 84.0,
          vehicleTypeStatistics: [
            { typeName: "重型卡车", runningCount: 10, nonRunningCount: 2 },
            { typeName: "轻型货车", runningCount: 28, nonRunningCount: 5 },
            { typeName: "冷链车", runningCount: 4, nonRunningCount: 1 }
          ],
          systemOperationMetrics: {
            resourceUtilization: 91.5,
            cost: 58340.5,
            totalTime: 350.2,
            totalDistance: 62000.7,
            carbonEmissions: 1204.3,
            satisfaction: 98.2
          },
          systemPerformanceMetrics: {
            resourceUtilizationScore: 91.5,
            costScore: 88.0,
            timeScore: 85.5,
            distanceScore: 86.0,
            carbonEmissionsScore: 82.1,
            satisfactionScore: 98.2
          },
          vehicleStatusStatistics: {
            normalPercentage: 75.0,
            slowPercentage: 15.0,
            congestedPercentage: 5.0,
            errorPercentage: 5.0
          },
          anomalyEvents: [
            { name: "车辆故障", count: 5, description: "严重" },
            { name: "派送超时", count: 3, description: "中等" },
            { name: "道路拥堵", count: 2, description: "轻微" }
          ],
          totalAnomalyEventCount: 10,
          vehicleProfiles: [
            { vehicleId: "VN-001", vehicleType: "Heavy Truck", totalCost: 1895.0, fixedCost: 501.0, depreciationCost: 81.0, oilCost: 1313.0 },
            { vehicleId: "VN-002", vehicleType: "Heavy Truck", totalCost: 1898.0, fixedCost: 502.0, depreciationCost: 82.0, oilCost: 1314.0 },
            { vehicleId: "VN-003", vehicleType: "Heavy Truck", totalCost: 1901.0, fixedCost: 503.0, depreciationCost: 83.0, oilCost: 1315.0 },
            { vehicleId: "VN-004", vehicleType: "Heavy Truck", totalCost: 1904.0, fixedCost: 504.0, depreciationCost: 84.0, oilCost: 1316.0 },
            { vehicleId: "VN-005", vehicleType: "Heavy Truck", totalCost: 1907.0, fixedCost: 505.0, depreciationCost: 85.0, oilCost: 1317.0 },
            { vehicleId: "VN-006", vehicleType: "Heavy Truck", totalCost: 1910.0, fixedCost: 506.0, depreciationCost: 86.0, oilCost: 1318.0 },
            { vehicleId: "VN-007", vehicleType: "Heavy Truck", totalCost: 1913.0, fixedCost: 507.0, depreciationCost: 87.0, oilCost: 1319.0 },
            { vehicleId: "VN-008", vehicleType: "Heavy Truck", totalCost: 1916.0, fixedCost: 508.0, depreciationCost: 88.0, oilCost: 1320.0 },
            { vehicleId: "VN-009", vehicleType: "Heavy Truck", totalCost: 1919.0, fixedCost: 509.0, depreciationCost: 89.0, oilCost: 1321.0 },
            { vehicleId: "VN-0010", vehicleType: "Heavy Truck", totalCost: 1922.0, fixedCost: 510.0, depreciationCost: 90.0, oilCost: 1322.0 }
          ],
          configuration: {
            optimizationMethod: "WEIGHTED",
            weather: "RAINY",
            supplyChainSupport: true,
            vehicleRestConfig: { enabled: true, durationHours: 6 },
            cargoLossRate: 0.015,
            trafficCongestionLevel: 0.45,
            vehicleFailureRate: 0.005,
            timeStepMinutes: 15,
            iterationCount: 2000
          }
        };
      }
    }

    // 更新页面数据
    function updatePageData(data) {
      // 更新运行参数数据
      updateConfigurationData(data);
      try {
        // 确保data对象有效
        if (!data) {
          console.error('更新页面数据失败: 数据为空');
          return;
        }

        // 更新页面标题
        const headerTitle = document.querySelector('header h1');
        if (headerTitle && data.optimizationName) {
          headerTitle.textContent = data.optimizationName;
        }

        // 更新车辆统计
        const vehicleStatsElements = document.querySelectorAll('.text-2xl.font-bold.text-white.text-center');
        if (vehicleStatsElements.length >= 2 && typeof data.totalVehicleCount === 'number' && typeof data.runningVehicleCount === 'number') {
          vehicleStatsElements[0].innerHTML = formatNumberWithHighlight(data.totalVehicleCount);
          vehicleStatsElements[1].innerHTML = formatNumberWithHighlight(data.runningVehicleCount);
        }

        // 更新运行占比
        const runningRatioElement = document.getElementById('runningRatio');
        if (runningRatioElement && typeof data.runningVehiclePercentage === 'number') {
          runningRatioElement.textContent = `运行占比: ${data.runningVehiclePercentage.toFixed(1)}%`;
        }

        // 更新系统运行指标
        const metrics = data.systemOperationMetrics;
        if (metrics) {
          // 使用ID直接获取元素，避免选择器问题
          const resourceUtilEl = document.getElementById('resourceUtil');
          if (resourceUtilEl && typeof metrics.resourceUtilization === 'number') {
            resourceUtilEl.textContent = `${metrics.resourceUtilization.toFixed(1)}%`;
          }

          const costEl = document.getElementById('totalCost');
          if (costEl && typeof metrics.cost === 'number') {
            costEl.textContent = `¥${Math.round(metrics.cost).toLocaleString()}`;
          }

          const timeEl = document.getElementById('totalTime');
          if (timeEl && typeof metrics.totalTime === 'number') {
            timeEl.textContent = `${metrics.totalTime.toFixed(1)} 分钟`;
          }

          const distanceEl = document.getElementById('totalDistance');
          if (distanceEl && typeof metrics.totalDistance === 'number') {
            distanceEl.textContent = `${Math.round(metrics.totalDistance).toLocaleString()} km`;
          }

          const carbonEl = document.getElementById('carbonEmissions');
          if (carbonEl && typeof metrics.carbonEmissions === 'number') {
            carbonEl.textContent = `${metrics.carbonEmissions.toFixed(1)} 吨`;
          }

          const satisfactionEl = document.getElementById('satisfaction');
          if (satisfactionEl && typeof metrics.satisfaction === 'number') {
            satisfactionEl.textContent = `${metrics.satisfaction.toFixed(1)}%`;
          }
        }

        // 更新异常事件数量
        const anomalyCountElement = document.getElementById('anomalyCount');
        if (anomalyCountElement && typeof data.totalAnomalyEventCount === 'number') {
          anomalyCountElement.textContent = `${data.totalAnomalyEventCount} 起`;
        }

        // 更新异常事件列表
        const anomalyEventsContainer = document.getElementById('anomalyEventsContainer');
        if (anomalyEventsContainer && Array.isArray(data.anomalyEvents)) {
          // 清空现有列表
          anomalyEventsContainer.innerHTML = '';

          // 定义异常事件严重程度对应的颜色
          const severityColors = {
            '严重': 'border-accent',
            '中等': 'border-yellow-400',
            '轻微': 'border-yellow-400'
          };

          // 根据事件数量和类型创建异常事件项
          data.anomalyEvents.forEach(event => {
            // 确保事件对象有必要的属性
            if (!event.name || typeof event.count !== 'number' || !event.description) {
              return;
            }

            const severity = event.description;

            // 创建事件项元素
            const eventItem = document.createElement('div');
            eventItem.className = `bg-darker p-3 rounded-lg border-l-2 ${severityColors[severity] || 'border-yellow-400'}`;

            // 设置事件项内容
            eventItem.innerHTML = `
              <div class="flex justify-between items-start mb-1">
                <span class="text-sm font-medium">${event.name}</span>
              </div>
              <div class="flex justify-between text-xs">
                <span>数量: ${event.count}起</span>
                <span class="${severity === '严重' ? 'text-accent' : 'text-yellow-400'}">${severity}</span>
              </div>
            `;

            // 添加到容器
            anomalyEventsContainer.appendChild(eventItem);
          });
        }
      } catch (error) {
        console.error('更新页面数据过程中发生错误:', error);
      }
    }

    // 格式化数字并高亮显示中间数字
    function formatNumberWithHighlight(num) {
      const numStr = num.toString();
      if (numStr.length === 2) {
        return `<span class="text-primary">${numStr[0]}</span>${numStr[1]}`;
      } else if (numStr.length === 3) {
        return `${numStr[0]}<span class="text-primary">${numStr[1]}</span>${numStr[2]}`;
      }
      return numStr;
    }

    // 所有图表的初始化函数
    function initializeAllCharts(data) {
      // 首先销毁所有现有的图表实例
      Object.keys(chartInstances).forEach(chartId => {
        if (chartInstances[chartId]) {
          chartInstances[chartId].destroy();
          chartInstances[chartId] = null;
        }
      });
      // 计算车辆总成本
      function calculateTotalCost(costs) {
        return costs.reduce((sum, cost) => sum + cost, 0);
      }

      // 运行车辆成本明细图表 - 堆叠条形图显示各项成本明细
      const areaDensityCtx = document.getElementById('areaDensityChart').getContext('2d');

      // 准备车辆成本数据
      const vehicleProfiles = data.vehicleProfiles || [];
      const vehicleIds = vehicleProfiles.map(vehicle => vehicle.vehicleId);
      
      // 提取各项成本数据
      const fixedCosts = vehicleProfiles.map(vehicle => vehicle.fixedCost || 0);
      const depreciationCosts = vehicleProfiles.map(vehicle => vehicle.depreciationCost || 0);
      const oilCosts = vehicleProfiles.map(vehicle => vehicle.oilCost || 0);

      chartInstances.areaDensityChart = new Chart(areaDensityCtx, {
        type: 'bar',
        data: {
          labels: vehicleIds,
          datasets: [
            {
              label: '固定成本',
              data: fixedCosts,
              backgroundColor: 'rgba(54, 162, 235, 0.7)',
              borderColor: 'rgba(54, 162, 235, 1)',
              borderWidth: 1
            },
            {
              label: '折旧成本',
              data: depreciationCosts,
              backgroundColor: 'rgba(255, 206, 86, 0.7)',
              borderColor: 'rgba(255, 206, 86, 1)',
              borderWidth: 1
            },
            {
              label: '燃油成本',
              data: oilCosts,
              backgroundColor: 'rgba(255, 99, 132, 0.7)',
              borderColor: 'rgba(255, 99, 132, 1)',
              borderWidth: 1
            }
          ]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            x: {
              grid: {
                color: 'rgba(255, 255, 255, 0.05)'
              },
              ticks: {
                color: 'rgba(255, 255, 255, 0.7)',
                maxRotation: 45,
                minRotation: 45
              },
              stacked: true
            },
            y: {
              grid: {
                color: 'rgba(255, 255, 255, 0.05)'
              },
              ticks: {
                color: 'rgba(255, 255, 255, 0.7)'
              },
              stacked: true
            }
          },
          plugins: {
            legend: {
              position: 'top',
              labels: {
                color: 'rgba(255, 255, 255, 0.7)',
                font: {
                  size: 10
                },
                padding: 10
              }
            },
            tooltip: {
              backgroundColor: 'rgba(0, 0, 0, 0.9)',
              titleColor: '#ffffff',
              bodyColor: '#ffffff',
              borderColor: '#00a3ff',
              borderWidth: 1,
              padding: 10,
              cornerRadius: 4,
              callbacks: {
                // 自定义tooltip显示，包含所有详细信息
                afterLabel: function(context) {
                  const index = context.dataIndex;
                  const vehicle = vehicleProfiles[index];
                  if (!vehicle) return '';
                  
                  const totalCost = vehicle.totalCost || (fixedCosts[index] + depreciationCosts[index] + oilCosts[index]);
                  const vehicleType = vehicle.vehicleType || '未知类型';
                  const fixedCost = vehicle.fixedCost || 0;
                  const depreciationCost = vehicle.depreciationCost || 0;
                  const oilCost = vehicle.oilCost || 0;
                  
                  return [
                    `车辆ID: ${vehicle.vehicleId}`,
                    `车辆类型: ${vehicleType}`,
                    `总成本: ¥${totalCost.toFixed(2)}`,
                    `固定成本: ¥${fixedCost.toFixed(2)}`,
                    `折旧成本: ¥${depreciationCost.toFixed(2)}`,
                    `燃油成本: ¥${oilCost.toFixed(2)}`
                  ];
                }
              }
            }
          },
          stacked: true
        }
      });

      // 车辆状态统计图表 - 使用从API获取的车辆状态数据
      const vehicleStatusCtx = document.getElementById('vehicleStatusChart').getContext('2d');
      const statusStats = data.vehicleStatusStatistics || { normalPercentage: 75, slowPercentage: 15, congestedPercentage: 5, errorPercentage: 5 };

      chartInstances.vehicleStatusChart = new Chart(vehicleStatusCtx, {
        type: 'doughnut',
        data: {
          labels: ['正常运行', '缓行', '拥堵', '异常状态'],
          datasets: [{
            data: [statusStats.normalPercentage, statusStats.slowPercentage, statusStats.congestedPercentage, statusStats.errorPercentage],
            backgroundColor: [
              '#4ade80',
              '#facc15',
              '#fb923c',
              '#ef4444'
            ],
            borderWidth: 0,
            hoverOffset: 4
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          cutout: '70%',
          plugins: {
            legend: {
              position: 'bottom',
              labels: {
                color: 'rgba(255, 255, 255, 0.7)',
                font: {
                  size: 10
                },
                padding: 10
              }
            }
          }
        }
      });

      // 车辆类型分布图表 - 堆叠条形图 - 使用从API获取的车辆类型数据
      const vehicleTypeCtx = document.getElementById('vehicleTypeChart').getContext('2d');
      const typeStats = data.vehicleTypeStatistics || [];

      // 车辆类型的预设颜色
      const typeColors = {
        '重型卡车': ['#00a3ff', 'rgba(0, 163, 255, 0.3)'],
        '轻型货车': ['#00ffdd', 'rgba(0, 255, 221, 0.3)'],
        '冷链车': ['#a855f7', 'rgba(168, 85, 247, 0.3)']
      };

      const defaultColors = ['#ff3d71', 'rgba(255, 61, 113, 0.3)'];

      const typeLabels = typeStats.map(type => type.typeName);
      const runningData = typeStats.map(type => type.runningCount);
      const nonRunningData = typeStats.map(type => type.nonRunningCount);

      // 为每种类型准备颜色
      const runningColors = [];
      const nonRunningColors = [];

      typeStats.forEach((type, index) => {
        const colors = typeColors[type.typeName] || defaultColors;
        runningColors.push(colors[0]);
        nonRunningColors.push(colors[1]);
      });

      chartInstances.vehicleTypeChart = new Chart(vehicleTypeCtx, {
        type: 'bar',
        data: {
          labels: typeLabels,
          datasets: [
            {
              label: '运行车辆数',
              data: runningData,
              backgroundColor: runningColors,
              borderWidth: 0,
              borderRadius: 4
            },
            {
              label: '非运行车辆数',
              data: nonRunningData,
              backgroundColor: nonRunningColors,
              borderWidth: 0,
              borderRadius: 4
            }
          ]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          indexAxis: 'y',
          scales: {
            x: {
              stacked: true,
              grid: {
                display: false,
                drawBorder: false
              },
              ticks: {
                color: 'rgba(255, 255, 255, 0.6)',
                font: {
                  size: 10
                }
              }
            },
            y: {
              stacked: true,
              grid: {
                display: false,
                drawBorder: false
              },
              ticks: {
                color: 'rgba(255, 255, 255, 0.7)',
                font: {
                  size: 11
                }
              }
            }
          },
          plugins: {
            legend: {
              position: 'top',
              labels: {
                color: 'rgba(255, 255, 255, 0.7)',
                font: {
                  size: 10
                },
                padding: 10
              }
            },
            tooltip: {
              backgroundColor: 'rgba(0, 0, 0, 0.8)',
              titleColor: 'white',
              bodyColor: 'white',
              borderColor: '#00a3ff',
              borderWidth: 1,
              callbacks: {
                afterLabel: function (context) {
                  // 获取当前图表实例
                  const chart = context.chart;

                  // 获取运行车辆数和非运行车辆数
                  const runningVehicles = chart.data.datasets[0].data[context.dataIndex];
                  const nonRunningVehicles = chart.data.datasets[1].data[context.dataIndex];

                  // 计算总车辆数
                  const totalVehicles = runningVehicles + nonRunningVehicles;

                  // 计算运行车辆占比
                  const runningPercentage = ((runningVehicles / totalVehicles) * 100).toFixed(1);

                  return `总车辆数: ${totalVehicles} 辆 (运行率: ${runningPercentage}%)`;
                }
              }
            }
          }
        }
      });



      // 系统性能指标图表 - 使用从API获取的性能数据

      // 系统性能指标图表 - 使用从API获取的性能数据
      const efficiencyCtx = document.getElementById('efficiencyChart').getContext('2d');
      const performanceData = data.systemPerformanceMetrics || {};

      chartInstances.efficiencyChart = new Chart(efficiencyCtx, {
        type: 'radar',
        data: {
          labels: ['资源利用率', '成本控制', '时间效率', '距离优化', '碳排放', '满意度'],
          datasets: [{
            label: '当前状态',
            data: [
              performanceData.resourceUtilizationScore || 78.5,
              performanceData.costScore || 88.0,
              performanceData.timeScore || 76,
              performanceData.distanceScore || 85,
              performanceData.carbonEmissionsScore || 68,
              performanceData.satisfactionScore || 92.7
            ],
            backgroundColor: 'rgba(0, 163, 255, 0.2)',
            borderColor: 'rgba(0, 163, 255, 0.8)',
            pointBackgroundColor: 'rgba(0, 163, 255, 1)',
            pointBorderColor: '#fff',
            pointHoverBackgroundColor: '#fff',
            pointHoverBorderColor: 'rgba(0, 163, 255, 1)'
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          scales: {
            r: {
              angleLines: {
                color: 'rgba(255, 255, 255, 0.1)'
              },
              grid: {
                color: 'rgba(255, 255, 255, 0.1)'
              },
              pointLabels: {
                color: 'rgba(255, 255, 255, 0.7)',
                font: {
                  size: 10
                }
              },
              ticks: {
                color: 'rgba(255, 255, 255, 0.5)',
                backdropColor: 'transparent',
                font: {
                  size: 8
                }
              }
            }
          },
          plugins: {
            legend: {
              position: 'bottom',
              labels: {
                color: 'rgba(255, 255, 255, 0.7)',
                font: {
                  size: 10
                },
                padding: 10
              }
            }
          }
        }
      });
    }

    // 更新运行参数数据
    function updateConfigurationData(data) {
      if (!data || !data.configuration) {
        console.error('更新运行参数失败: 配置数据为空');
        return;
      }

      const config = data.configuration;
      const configContainer = document.getElementById('configurationData');

      if (!configContainer) return;

      // 清空现有内容
      configContainer.innerHTML = '';

      // 配置项的中文映射
      const configLabels = {
        optimizationMethod: '优化方法',
        weather: '天气条件',
        supplyChainSupport: '供应链支持',
        cargoLossRate: '货物损失率',
        trafficCongestionLevel: '交通拥堵等级',
        vehicleFailureRate: '车辆故障率',
        timeStepMinutes: '时间步长(分钟)',
        iterationCount: '迭代次数'
      };

      // 天气条件映射
      const weatherMap = {
        'SUNNY': '晴朗',
        'RAINY': '下雨',
        'CLOUDY': '多云',
        'SNOWY': '下雪'
      };

      // 优化方法映射
      const methodMap = {
        'WEIGHTED': '加权优化',
        'GREEDY': '贪心算法',
        'GENETIC': '遗传算法',
        'PREDICTIVE': '预测优化'
      };

      // 创建配置项元素
      function createConfigItem(label, value) {
        const item = document.createElement('div');
        item.className = 'flex justify-between items-center py-2 border-b border-dark-border';
        item.innerHTML = `
          <span class="text-gray-300">${label}</span>
          <span class="text-white font-medium">${value}</span>
        `;
        return item;
      }

      // 添加主配置项
      for (const key in config) {
        if (key === 'vehicleRestConfig') {
          // 特殊处理车辆休息配置
          const restConfig = config[key];
          configContainer.appendChild(createConfigItem('车辆休息配置', restConfig.enabled ? `启用 (${restConfig.durationHours}小时)` : '禁用'));
        } else if (configLabels[key]) {
          let displayValue = config[key];

          // 特殊格式化
          if (key === 'weather' && weatherMap[displayValue]) {
            displayValue = weatherMap[displayValue];
          } else if (key === 'optimizationMethod' && methodMap[displayValue]) {
            displayValue = methodMap[displayValue];
          } else if (typeof displayValue === 'boolean') {
            displayValue = displayValue ? '启用' : '禁用';
          } else if (typeof displayValue === 'number' && (key.includes('Rate') || key.includes('Level'))) {
            displayValue = (displayValue * 100).toFixed(1) + '%';
          }

          configContainer.appendChild(createConfigItem(configLabels[key], displayValue));
        }
      }
    }

    // 全局变量，用于存储API数据和图表实例
    let globalSimulationRecords = null;
    // 存储图表实例的对象，用于后续更新或销毁
    let chartInstances = {
      areaDensityChart: null,
      vehicleStatusChart: null,
      vehicleTypeChart: null,
      efficiencyChart: null
    };
    
    // 初始化运行参数按钮事件
    document.addEventListener('DOMContentLoaded', function () {
      // 初始化模拟记录侧边栏
      initializeSimulationSidebar();
      // 获取并显示模拟记录，同时存储到全局变量供其他函数使用
      fetchAndDisplaySimulationRecords().then(() => {
        // 模拟记录加载完成后，如果地图已经初始化，则更新页面数据
        if (typeof map !== 'undefined') {
          fetchDataAndUpdatePage();
        }
      });

      // 初始化添加模拟运行模态框
      const addSimulationBtn = document.getElementById('addSimulationBtn');
      const addSimulationModal = document.getElementById('addSimulationModal');
      const closeAddSimulationBtn = document.getElementById('closeAddSimulationBtn');
      const cancelAddSimulationBtn = document.getElementById('cancelAddSimulationBtn');
      const submitSimulationBtn = document.getElementById('submitSimulationBtn');
      const vehicleRestEnabled = document.getElementById('vehicleRestEnabled');
      const restDurationContainer = document.getElementById('restDurationContainer');
      const addVehicleTypeBtn = document.getElementById('addVehicleTypeBtn');
      const vehicleTypesContainer = document.getElementById('vehicleTypesContainer');
      const costPriorityBtn = document.getElementById('costPriorityBtn');
      const efficiencyPriorityBtn = document.getElementById('efficiencyPriorityBtn');
      const greenPriorityBtn = document.getElementById('greenPriorityBtn');
      
      // 默认方案配置
       const defaultSchemes = {
         // 成本优先方案
         costPriority: {
           optimizationName: '成本优先方案',
           totalVehicleCount: 30,
           optimizationMethod: 'WEIGHTED',
           weightedWeights: [10, 40, 20, 20, 5, 5], // 资源利用率、总成本、总时间、总距离、碳排放、满意度
           weather: 'SUNNY',
           supplyChainSupport: false,
           vehicleRestEnabled: false,
           cargoLossRate: 0.01,
           trafficCongestionLevel: 0.3,
           vehicleFailureRate: 0.005,
           timeStepMinutes: 30,
           iterationCount: 50
         },
         
         // 效率优先方案
         efficiencyPriority: {
           optimizationName: '效率优先方案',
           totalVehicleCount: 30,
           optimizationMethod: 'WEIGHTED',
           weightedWeights: [35, 15, 30, 10, 5, 5], // 资源利用率、总成本、总时间、总距离、碳排放、满意度
           weather: 'SUNNY',
           supplyChainSupport: true,
           vehicleRestEnabled: true,
           restDurationHours: 2,
           cargoLossRate: 0.02,
           trafficCongestionLevel: 0.2,
           vehicleFailureRate: 0.003,
           timeStepMinutes: 15,
           iterationCount: 100
         },
         
         // 环保优先方案
         greenPriority: {
           optimizationName: '环保优先方案',
           totalVehicleCount: 30,
           optimizationMethod: 'WEIGHTED',
           weightedWeights: [15, 10, 20, 15, 30, 10], // 资源利用率、总成本、总时间、总距离、碳排放、满意度
           weather: 'CLOUDY',
           supplyChainSupport: true,
           vehicleRestEnabled: true,
           restDurationHours: 1,
           cargoLossRate: 0.01,
           trafficCongestionLevel: 0.4,
           vehicleFailureRate: 0.002,
           timeStepMinutes: 20,
           iterationCount: 80
         }
       };
      
      // 应用默认方案
      function applyScheme(schemeName) {
        const scheme = defaultSchemes[schemeName];
        if (!scheme) return;
        
        // 应用基本字段
        document.getElementById('optimizationName').value = scheme.optimizationName;
        document.getElementById('totalVehicleCount').value = scheme.totalVehicleCount;
        document.getElementById('optimizationMethod').value = scheme.optimizationMethod;
        document.getElementById('weather').value = scheme.weather;
        document.getElementById('supplyChainSupport').checked = scheme.supplyChainSupport;
        document.getElementById('vehicleRestEnabled').checked = scheme.vehicleRestEnabled;
        document.getElementById('restDurationHours').value = scheme.restDurationHours || '';
        document.getElementById('cargoLossRate').value = scheme.cargoLossRate;
        document.getElementById('trafficCongestionLevel').value = scheme.trafficCongestionLevel;
        document.getElementById('vehicleFailureRate').value = scheme.vehicleFailureRate;
        document.getElementById('timeStepMinutes').value = scheme.timeStepMinutes;
        document.getElementById('iterationCount').value = scheme.iterationCount;
        
        // 显示或隐藏休息时长容器
        if (scheme.vehicleRestEnabled) {
          document.getElementById('restDurationContainer').classList.remove('hidden');
        } else {
          document.getElementById('restDurationContainer').classList.add('hidden');
        }
        
        // 应用加权优化权重
        if (scheme.weightedWeights) {
          const weightedInputs = document.querySelectorAll('.weighted-weight');
          scheme.weightedWeights.forEach((weight, index) => {
            if (weightedInputs[index]) {
              weightedInputs[index].value = weight;
            }
          });
          
          // 触发权重计算
          calculateWeightedSum();
        }
        
        // 添加默认车辆类型配置
        const vehicleTypesContainer = document.getElementById('vehicleTypesContainer');
        // 清除所有行，只保留第一行
        const items = vehicleTypesContainer.querySelectorAll('.vehicle-type-item');
        for (let i = 1; i < items.length; i++) {
          items[i].remove();
        }
        
        // 根据方案添加车辆类型
        let vehicleTypes = [];
        if (schemeName === 'costPriority') {
          vehicleTypes = [
            {name: '经济型货车', count: 20},
            {name: '标准货车', count: 10}
          ];
        } else if (schemeName === 'efficiencyPriority') {
          vehicleTypes = [
            {name: '高效货车', count: 20},
            {name: '标准货车', count: 10}
          ];
        } else if (schemeName === 'greenPriority') {
          vehicleTypes = [
            {name: '电动货车', count: 15},
            {name: '混合动力货车', count: 10},
            {name: '标准货车', count: 5}
          ];
        }
        
        // 确保容器和第一行存在
        if (vehicleTypesContainer && vehicleTypes.length > 0) {
          // 检查是否有第一行，如果没有则创建
          let firstVehicleItem = vehicleTypesContainer.querySelector('.vehicle-type-item');
          if (!firstVehicleItem) {
            firstVehicleItem = document.createElement('div');
            firstVehicleItem.className = 'vehicle-type-item flex items-center space-x-2';
            firstVehicleItem.innerHTML = `
              <input type="text" class="flex-grow bg-darker border border-dark-border rounded px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary/50">
              <input type="number" min="1" class="w-20 bg-darker border border-dark-border rounded px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary/50">
              <button class="remove-vehicle-type text-gray-400 hover:text-accent">
                <i class="fa fa-trash"></i>
              </button>
            `;
            vehicleTypesContainer.appendChild(firstVehicleItem);
          }
          
          // 填充第一行数据
          const firstType = vehicleTypes[0];
          const inputs = firstVehicleItem.querySelectorAll('input');
          if (inputs.length >= 2) {
            inputs[0].value = firstType.name;
            inputs[1].value = firstType.count;
          }
          
          // 绑定第一行的移除按钮（如果有）
          const removeBtn = firstVehicleItem.querySelector('.remove-vehicle-type');
          if (removeBtn) {
            // 保留第一行的移除按钮事件，但防止删除唯一一行
            removeBtn.addEventListener('click', function () {
              if (vehicleTypesContainer.querySelectorAll('.vehicle-type-item').length > 1) {
                firstVehicleItem.remove();
              }
            });
          }
          
          // 添加剩余的车辆类型
          for (let i = 1; i < vehicleTypes.length; i++) {
            const type = vehicleTypes[i];
            const newVehicleType = document.createElement('div');
            newVehicleType.className = 'vehicle-type-item flex items-center space-x-2';
            newVehicleType.innerHTML = `
              <input type="text" value="${type.name}" class="flex-grow bg-darker border border-dark-border rounded px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary/50">
              <input type="number" value="${type.count}" min="1" class="w-20 bg-darker border border-dark-border rounded px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary/50">
              <button class="remove-vehicle-type text-gray-400 hover:text-accent">
                <i class="fa fa-trash"></i>
              </button>
            `;
            
            vehicleTypesContainer.appendChild(newVehicleType);
            
            // 为新添加的移除按钮绑定事件
            const removeBtn = newVehicleType.querySelector('.remove-vehicle-type');
            if (removeBtn) {
              removeBtn.addEventListener('click', function () {
                newVehicleType.remove();
              });
            }
          }
        }
      }

      // 显示添加模拟运行模态框
      if (addSimulationBtn && addSimulationModal) {
        addSimulationBtn.addEventListener('click', function () {
          resetSimulationForm(); // 显示前重置表单（不包括车辆类型配置）
          addSimulationModal.classList.remove('hidden');
          addSimulationModal.classList.add('flex');
        });
      }

      // 关闭添加模拟运行模态框
      function closeModal() {
        if (addSimulationModal) {
          addSimulationModal.classList.add('hidden');
          addSimulationModal.classList.remove('flex');
        }
      }

      if (closeAddSimulationBtn) {
        closeAddSimulationBtn.addEventListener('click', closeModal);
      }

      if (cancelAddSimulationBtn) {
        cancelAddSimulationBtn.addEventListener('click', closeModal);
      }

      if (addSimulationModal) {
        // 点击模态框外部关闭
        addSimulationModal.addEventListener('click', function (event) {
          if (event.target === addSimulationModal) {
            closeModal();
          }
        });
      }

      // 车辆休息配置的显示/隐藏
      if (vehicleRestEnabled && restDurationContainer) {
        vehicleRestEnabled.addEventListener('change', function () {
          if (this.checked) {
            restDurationContainer.classList.remove('hidden');
          } else {
            restDurationContainer.classList.add('hidden');
          }
        });
      }

      // 添加车辆类型
      if (addVehicleTypeBtn && vehicleTypesContainer) {
        addVehicleTypeBtn.addEventListener('click', function () {
          const newVehicleType = document.createElement('div');
          newVehicleType.className = 'vehicle-type-item flex items-center space-x-2';
          newVehicleType.innerHTML = `
            <input type="text" placeholder="车辆类型名称" class="flex-grow bg-darker border border-dark-border rounded px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary/50">
            <input type="number" placeholder="数量" min="1" class="w-20 bg-darker border border-dark-border rounded px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary/50">
            <button class="remove-vehicle-type text-gray-400 hover:text-accent">
              <i class="fa fa-trash"></i>
            </button>
          `;

          vehicleTypesContainer.appendChild(newVehicleType);

          // 为新添加的移除按钮绑定事件
          const removeBtn = newVehicleType.querySelector('.remove-vehicle-type');
          if (removeBtn) {
            removeBtn.addEventListener('click', function () {
              newVehicleType.remove();
            });
          }
        });
      }
      
      // 默认方案按钮事件监听
      if (costPriorityBtn) {
        costPriorityBtn.addEventListener('click', function() {
          applyScheme('costPriority');
          highlightActiveSchemeBtn(costPriorityBtn);
        });
      }
      
      if (efficiencyPriorityBtn) {
        efficiencyPriorityBtn.addEventListener('click', function() {
          applyScheme('efficiencyPriority');
          highlightActiveSchemeBtn(efficiencyPriorityBtn);
        });
      }
      
      if (greenPriorityBtn) {
        greenPriorityBtn.addEventListener('click', function() {
          applyScheme('greenPriority');
          highlightActiveSchemeBtn(greenPriorityBtn);
        });
      }
      
      // 高亮显示当前选中的方案按钮
      function highlightActiveSchemeBtn(activeBtn) {
        const allSchemeBtns = [costPriorityBtn, efficiencyPriorityBtn, greenPriorityBtn];
        allSchemeBtns.forEach(btn => {
          if (btn) {
            if (btn === activeBtn) {
              btn.classList.add('bg-primary/20', 'text-primary');
              btn.classList.remove('bg-dark-border', 'text-gray-300');
            } else {
              btn.classList.remove('bg-primary/20', 'text-primary');
              btn.classList.add('bg-dark-border', 'text-gray-300');
            }
          }
        });
      }

      // 为初始的移除按钮绑定事件
      const initialRemoveBtns = document.querySelectorAll('.remove-vehicle-type');
      initialRemoveBtns.forEach(btn => {
        btn.addEventListener('click', function () {
          const item = this.closest('.vehicle-type-item');
          if (item) {
            item.remove();
          }
        });
      });

      // 优化权重相关逻辑
      const optimizationMethod = document.getElementById('optimizationMethod');
      const hierarchicalWeights = document.getElementById('hierarchicalWeights');
      const weightedWeights = document.getElementById('weightedWeights');
      const goalProgrammingWeights = document.getElementById('goalProgrammingWeights');
      const weightedSumElement = document.getElementById('weightedSum');
      
      // 监听优化方法变化
      if (optimizationMethod && hierarchicalWeights && weightedWeights && goalProgrammingWeights) {
        optimizationMethod.addEventListener('change', function() {
          const method = this.value;
          
          // 隐藏所有权重配置区域
          hierarchicalWeights.classList.add('hidden');
          weightedWeights.classList.add('hidden');
          goalProgrammingWeights.classList.add('hidden');
          
          // 根据选择的方法显示对应的配置区域
          if (method === 'HIERARCHICAL') {
            hierarchicalWeights.classList.remove('hidden');
          } else if (method === 'WEIGHTED') {
            weightedWeights.classList.remove('hidden');
            updateWeightedSum(); // 更新加权总和
          } else if (method === 'GOAL_PROGRAMMING') {
            goalProgrammingWeights.classList.remove('hidden');
          }
        });
      }
      
      // 监听加权权重输入变化
      const weightedWeightInputs = document.querySelectorAll('.weighted-weight');
      weightedWeightInputs.forEach(input => {
        input.addEventListener('input', updateWeightedSum);
      });
      
      // 更新加权总和
      function updateWeightedSum() {
        if (!weightedSumElement) return;
        
        let sum = 0;
        weightedWeightInputs.forEach(input => {
          const value = parseInt(input.value) || 0;
          sum += value;
        });
        weightedSumElement.textContent = sum;
        
        // 添加视觉反馈
        if (sum !== 100) {
          weightedSumElement.classList.add('text-red-400');
          weightedSumElement.classList.remove('text-green-400');
        } else {
          weightedSumElement.classList.remove('text-red-400');
          weightedSumElement.classList.add('text-green-400');
        }
      }

      // 提交模拟运行
      if (submitSimulationBtn) {
        submitSimulationBtn.addEventListener('click', function () {
          submitNewSimulation();
        });
      }
      const configBtn = document.getElementById('configurationBtn');
      const configModal = document.getElementById('configurationModal');
      const closeBtn = document.getElementById('closeConfigurationBtn');
      const bottomCloseBtn = document.getElementById('bottomCloseBtn');

      if (configBtn && configModal) {
        // 显示运行参数模态框
        configBtn.addEventListener('click', function () {
          configModal.classList.remove('hidden');
          configModal.classList.add('flex');
        });

        // 关闭运行参数模态框
        if (closeBtn) {
          closeBtn.addEventListener('click', function () {
            configModal.classList.add('hidden');
            configModal.classList.remove('flex');
          });
        }

        // 底部关闭按钮事件
        if (bottomCloseBtn) {
          bottomCloseBtn.addEventListener('click', function () {
            configModal.classList.add('hidden');
            configModal.classList.remove('flex');
          });
        }

        // 点击模态框外部关闭
        configModal.addEventListener('click', function (event) {
          if (event.target === configModal) {
            configModal.classList.add('hidden');
            configModal.classList.remove('flex');
          }
        });
      }
    });

    // 提交新的模拟运行
    async function submitNewSimulation() {
      try {
        // 获取表单数据
        const optimizationName = document.getElementById('optimizationName').value;
        const totalVehicleCount = parseInt(document.getElementById('totalVehicleCount').value);
        const optimizationMethod = document.getElementById('optimizationMethod').value;
        const weather = document.getElementById('weather').value;
        const supplyChainSupport = document.getElementById('supplyChainSupport').checked;
        const vehicleRestEnabled = document.getElementById('vehicleRestEnabled').checked;
        const restDurationHours = vehicleRestEnabled ? parseInt(document.getElementById('restDurationHours').value) : 0;
        const cargoLossRate = parseFloat(document.getElementById('cargoLossRate').value || 0);
        const trafficCongestionLevel = parseFloat(document.getElementById('trafficCongestionLevel').value || 0);
        const vehicleFailureRate = parseFloat(document.getElementById('vehicleFailureRate').value || 0);
        const timeStepMinutes = parseInt(document.getElementById('timeStepMinutes').value || 0);
        const iterationCount = parseInt(document.getElementById('iterationCount').value || 0);

        // 验证必填字段
        if (!optimizationName || isNaN(totalVehicleCount) || totalVehicleCount <= 0) {
          showNotification('请填写优化名称和有效的总车辆数', 'error');
          return;
        }

        // 获取车辆类型配置
        const vehicleTypeItems = document.querySelectorAll('.vehicle-type-item');
        const vehicleTypeCounts = [];
        let totalTypeCount = 0;

        vehicleTypeItems.forEach(item => {
          const typeName = item.querySelector('input[type="text"]').value;
          const typeCount = parseInt(item.querySelector('input[type="number"]').value);

          if (typeName && !isNaN(typeCount) && typeCount > 0) {
            vehicleTypeCounts.push({
              typeName: typeName,
              typeCount: typeCount
            });
            totalTypeCount += typeCount;
          }
        });

        // 验证车辆类型配置
        if (vehicleTypeCounts.length === 0) {
          showNotification('请至少添加一种车辆类型配置', 'error');
          return;
        }

        if (totalTypeCount !== totalVehicleCount) {
          showNotification(`车辆类型总数(${totalTypeCount})与总车辆数(${totalVehicleCount})不匹配`, 'error');
          return;
        }

        // 收集优化权重配置
        let optimizationWeights = [];
        let isValidWeights = true;
        
        if (optimizationMethod === 'HIERARCHICAL') {
          // 分层优化权重
          const hierarchicalSelects = document.querySelectorAll('.hierarchical-weight');
          hierarchicalSelects.forEach(select => {
            const value = parseInt(select.value);
            if (!isNaN(value) && value >= 1 && value <= 5) {
              optimizationWeights.push(value);
            } else {
              isValidWeights = false;
            }
          });
          
          if (!isValidWeights) {
            showNotification('请为分层优化选择有效的权重值 (1-5)', 'error');
            return;
          }
        } else if (optimizationMethod === 'WEIGHTED') {
          // 加权优化权重
          const weightedInputs = document.querySelectorAll('.weighted-weight');
          let sum = 0;
          weightedInputs.forEach(input => {
            const value = parseInt(input.value) || 0;
            if (value < 0 || value > 100) {
              isValidWeights = false;
            }
            optimizationWeights.push(value);
            sum += value;
          });
          
          if (!isValidWeights) {
            showNotification('加权优化权重值必须在0-100之间', 'error');
            return;
          }
          
          if (sum !== 100) {
            showNotification('加权优化权重总和必须为100', 'error');
            return;
          }
        } else if (optimizationMethod === 'GOAL_PROGRAMMING') {
          // 目标规划权重
          const goalProgrammingInputs = document.querySelectorAll('.goal-programming-weight');
          goalProgrammingInputs.forEach(input => {
            const value = parseInt(input.value) || 0;
            if (value < 0 || value > 100) {
              isValidWeights = false;
            }
            optimizationWeights.push(value);
          });
          
          if (!isValidWeights) {
            showNotification('目标规划权重值必须在0-100之间', 'error');
            return;
          }
        }

        // 构建请求参数
        const requestData = {
          optimizationName: optimizationName,
          totalVehicleCount: totalVehicleCount,
          vehicleTypeCounts: vehicleTypeCounts,
          configuration: {
            optimizationMethod: optimizationMethod,
            optimizationWeights: optimizationWeights,
            weather: weather,
            supplyChainSupport: supplyChainSupport,
            vehicleRestConfig: {
              enabled: vehicleRestEnabled,
              durationHours: restDurationHours
            },
            cargoLossRate: cargoLossRate,
            trafficCongestionLevel: trafficCongestionLevel,
            vehicleFailureRate: vehicleFailureRate,
            timeStepMinutes: timeStepMinutes,
            iterationCount: iterationCount
          }
        };

        // 发送POST请求
        const response = await fetch('http://localhost:8080/VRP/new', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(requestData)
        });

        if (!response.ok) {
          throw new Error('网络请求失败');
        }

        const data = await response.json();

        // 处理响应
        if (data.code === 200) {
          // 关闭模态框
          const addSimulationModal = document.getElementById('addSimulationModal');
          if (addSimulationModal) {
            addSimulationModal.classList.add('hidden');
            addSimulationModal.classList.remove('flex');
          }

          // 显示成功通知
          showNotification('模拟运行创建成功，后端正在处理中', 'success');

          // 清空表单
          resetSimulationForm();

          // 刷新模拟记录列表
          setTimeout(() => {
            fetchAndDisplaySimulationRecords();
          }, 1000);
        } else {
          showNotification(`创建失败: ${data.msg || '未知错误'}`, 'error');
        }
      } catch (error) {
        console.error('提交模拟运行失败:', error);
        showNotification(`创建失败: ${error.message}`, 'error');
      }
    }

    // 重置模拟运行表单
    function resetSimulationForm() {
      document.getElementById('optimizationName').value = '';
      document.getElementById('totalVehicleCount').value = '30'; // 默认总车辆数
      document.getElementById('optimizationMethod').value = 'WEIGHTED';
      document.getElementById('weather').value = 'SUNNY';
      document.getElementById('supplyChainSupport').checked = false;
      document.getElementById('vehicleRestEnabled').checked = false;
      document.getElementById('restDurationHours').value = '';
      document.getElementById('cargoLossRate').value = '';
      document.getElementById('trafficCongestionLevel').value = '';
      document.getElementById('vehicleFailureRate').value = '';
      document.getElementById('timeStepMinutes').value = '';
      document.getElementById('iterationCount').value = '';

      // 隐藏休息时长配置
      document.getElementById('restDurationContainer').classList.add('hidden');

      // 重置优化权重相关字段
      document.getElementById('weightedSum').textContent = '0';
      document.getElementById('weightedSum').classList.remove('text-red-400', 'text-green-400');
      
      // 重置分层优化权重
      const hierarchicalWeights = document.querySelectorAll('.hierarchical-weight');
      hierarchicalWeights.forEach(select => {
        select.value = '1'; // 默认选择最重要
      });
      
      // 重置加权优化权重
      const weightedWeights = document.querySelectorAll('.weighted-weight');
      weightedWeights.forEach(input => {
        input.value = '';
      });
      
      // 重置目标规划权重
      const goalProgrammingWeights = document.querySelectorAll('.goal-programming-weight');
      goalProgrammingWeights.forEach(input => {
        input.value = '';
      });
      
      // 重置权重配置区域的显示
      document.getElementById('hierarchicalWeights').classList.add('hidden');
      document.getElementById('weightedWeights').classList.remove('hidden');
      document.getElementById('goalProgrammingWeights').classList.add('hidden');
      
      // 添加默认的车辆类型配置
      const vehicleTypesContainer = document.getElementById('vehicleTypesContainer');
      // 保留一个空的车辆类型配置
      while (vehicleTypesContainer.children.length > 1) {
        vehicleTypesContainer.removeChild(vehicleTypesContainer.lastChild);
      }
      
      // 设置默认车辆类型和数量
      const remainingItem = vehicleTypesContainer.querySelector('.vehicle-type-item');
      if (remainingItem) {
        const typeNameInput = remainingItem.querySelector('input[type="text"]');
        const typeCountInput = remainingItem.querySelector('input[type="number"]');
        
        if (typeNameInput && typeCountInput) {
          typeNameInput.value = '标准货车';
          typeCountInput.value = '30';
        }
      }
    }

    // 显示通知
    function showNotification(message, type = 'info') {
      // 检查是否已有通知元素，如果有则移除
      const existingNotification = document.getElementById('notification');
      if (existingNotification) {
        existingNotification.remove();
      }

      // 创建通知元素
      const notification = document.createElement('div');
      notification.id = 'notification';

      // 根据类型设置样式
      let bgColor = 'bg-primary';
      if (type === 'success') {
        bgColor = 'bg-green-500';
      } else if (type === 'error') {
        bgColor = 'bg-accent';
      } else if (type === 'warning') {
        bgColor = 'bg-yellow-500';
      }

      notification.className = `fixed top-4 right-4 ${bgColor} text-white px-4 py-2 rounded-lg shadow-lg z-50 transform translate-x-full opacity-0 transition-all duration-500`;
      notification.innerHTML = `
        <div class="flex items-center">
          <span>${message}</span>
        </div>
      `;

      // 添加到页面
      document.body.appendChild(notification);

      // 显示通知
      setTimeout(() => {
        notification.classList.remove('translate-x-full', 'opacity-0');
      }, 100);

      // 3秒后隐藏通知
      setTimeout(() => {
        notification.classList.add('translate-x-full', 'opacity-0');
        // 动画结束后移除元素
        setTimeout(() => {
          notification.remove();
        }, 500);
      }, 3000);
    }

    // 初始化模拟记录侧边栏
    function initializeSimulationSidebar() {
      const toggleBtn = document.getElementById('toggleSimulationBtn');
      const sidebar = document.getElementById('simulationSidebar');
      const overlay = document.getElementById('sidebarOverlay');
      const closeBtn = document.getElementById('closeSidebarBtn');

      if (toggleBtn && sidebar && overlay && closeBtn) {
        // 切换侧边栏显示/隐藏
        toggleBtn.addEventListener('click', function () {
          sidebar.classList.toggle('-translate-x-full');
          overlay.classList.toggle('hidden');
        });

        // 关闭侧边栏
        closeBtn.addEventListener('click', function () {
          sidebar.classList.add('-translate-x-full');
          overlay.classList.add('hidden');
        });

        // 点击遮罩关闭侧边栏
        overlay.addEventListener('click', function () {
          sidebar.classList.add('-translate-x-full');
          overlay.classList.add('hidden');
        });
      }
    }

    // 从API获取并显示模拟记录
    async function fetchAndDisplaySimulationRecords() {
      try {
        // 先检查全局变量中是否已有数据
        if (globalSimulationRecords) {
          renderSimulationRecords(globalSimulationRecords);
          return;
        }
        
        const response = await fetch('http://localhost:8080/VRP/optimization/list');
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        const simulationRecords = await response.json();
        // 存储到全局变量供其他函数使用
        globalSimulationRecords = simulationRecords;
        renderSimulationRecords(simulationRecords);
      } catch (error) {
        console.error('Error fetching simulation records:', error);
        // 显示错误信息
        const container = document.getElementById('simulationRecordsContainer');
        if (container) {
          container.innerHTML = `
            <div class="flex justify-center items-center h-40 text-accent">
              <span>无法加载模拟记录，请稍后再试</span>
            </div>
          `;
        }
        // 在控制台打印详细错误
        console.error('详细错误:', error);
      }
    }

    // 渲染模拟记录列表
    function renderSimulationRecords(records) {
      const container = document.getElementById('simulationRecordsContainer');
      if (!container || !Array.isArray(records) || records.length === 0) {
        container.innerHTML = `
          <div class="flex justify-center items-center h-40 text-gray-400">
            <span>暂无模拟记录</span>
          </div>
        `;
        return;
      }

      // 清空容器
      container.innerHTML = '';

      // 渲染每条记录
      records.forEach(record => {
        const recordItem = createSimulationRecordItem(record);
        container.appendChild(recordItem);
      });
    }

    // 创建单个模拟记录项
    function createSimulationRecordItem(record) {
      const item = document.createElement('div');
      item.className = 'bg-dark-card rounded-lg p-3 border border-dark-border hover:border-primary/50 transition-all duration-300 cursor-pointer';

      // 格式化数据显示
      const runningPercentage = record.runningVehiclePercentage ? `${record.runningVehiclePercentage.toFixed(1)}%` : 'N/A';
      const totalCost = record.systemOperationMetrics?.cost ? `¥${Math.round(record.systemOperationMetrics.cost).toLocaleString()}` : 'N/A';
      const totalDistance = record.systemOperationMetrics?.totalDistance ? `${Math.round(record.systemOperationMetrics.totalDistance).toLocaleString()} km` : 'N/A';
      const anomalyCount = record.totalAnomalyEventCount || 0;

      // 设置记录项内容
      item.innerHTML = `
        <div class="flex justify-between items-start mb-2">
          <h4 class="font-medium text-white">${record.optimizationName || '未知模拟'}</h4>
          <span class="text-xs bg-primary/20 text-primary px-2 py-0.5 rounded-full">
            ${runningPercentage}
          </span>
        </div>
        <div class="space-y-1.5 text-xs">
          <div class="flex justify-between text-gray-300">
            <span>总车辆数</span>
            <span>${record.totalVehicleCount || 0}</span>
          </div>
          <div class="flex justify-between text-gray-300">
            <span>运行车辆数</span>
            <span class="text-primary">${record.runningVehicleCount || 0}</span>
          </div>
          <div class="flex justify-between text-gray-300">
            <span>总成本</span>
            <span>${totalCost}</span>
          </div>
          <div class="flex justify-between text-gray-300">
            <span>总距离</span>
            <span>${totalDistance}</span>
          </div>
          <div class="flex justify-between text-gray-300">
            <span>异常事件</span>
            <span class="${anomalyCount > 5 ? 'text-accent' : 'text-yellow-400'}">${anomalyCount} 起</span>
          </div>
        </div>
        <div class="mt-2 pt-2 border-t border-dark-border text-xs text-gray-400">
          <div class="flex justify-between">
            <span>优化方法: ${getOptimizationMethodName(record.configuration?.optimizationMethod)}</span>
          </div>
        </div>
      `;

      // 添加点击事件 - 点击后可以加载该记录的数据到主页面
      item.addEventListener('click', function () {
        updatePageWithSelectedRecord(record);
        // 关闭侧边栏
        document.getElementById('simulationSidebar').classList.add('-translate-x-full');
        document.getElementById('sidebarOverlay').classList.add('hidden');
      });

      return item;
    }

    // 获取优化方法的中文名称
    function getOptimizationMethodName(method) {
      const methodMap = {
        'WEIGHTED': '加权优化',
        'GREEDY': '贪心算法',
        'GENETIC': '遗传算法',
        'PREDICTIVE': '预测优化',
        '分层优化': '分层优化'
      };
      return methodMap[method] || method || '未知';
    }

    // 用选中的记录数据更新页面
    function updatePageWithSelectedRecord(record) {
      try {
        updatePageData(record);
        initializeAllCharts(record);
        // 可以添加一些视觉反馈，提示用户已加载新数据
        showDataUpdateNotification(record.optimizationName);
      } catch (error) {
        console.error('更新页面数据失败:', error);
      }
    }

    // 显示数据更新通知
    function showDataUpdateNotification(recordName) {
      // 检查是否已有通知元素，如果有则移除
      const existingNotification = document.getElementById('dataUpdateNotification');
      if (existingNotification) {
        existingNotification.remove();
      }

      // 创建通知元素
      const notification = document.createElement('div');
      notification.id = 'dataUpdateNotification';
      notification.className = 'fixed bottom-4 right-4 bg-primary text-white px-4 py-2 rounded-lg shadow-lg z-50 transform translate-y-16 opacity-0 transition-all duration-500';
      notification.innerHTML = `
        <div class="flex items-center">
          <i class="fa fa-refresh mr-2"></i>
          <span>已加载: ${recordName}</span>
        </div>
      `;

      // 添加到页面
      document.body.appendChild(notification);

      // 显示通知
      setTimeout(() => {
        notification.classList.remove('translate-y-16', 'opacity-0');
      }, 100);

      // 3秒后隐藏通知
      setTimeout(() => {
        notification.classList.add('translate-y-16', 'opacity-0');
        // 动画结束后移除元素
        setTimeout(() => {
          notification.remove();
        }, 500);
      }, 3000);
    }
  </script>

  <!-- 添加模拟运行模态框 -->
  <div id="addSimulationModal"
    class="fixed inset-0 z-50 hidden items-center justify-center bg-black/70 backdrop-blur-sm">
    <div
      class="bg-dark-card border border-dark-border rounded-lg shadow-xl w-full max-w-2xl max-h-[80vh] flex flex-col">
      <div class="p-4 border-b border-dark-border flex justify-between items-center">
        <h3 class="text-lg font-semibold text-white flex items-center">
          <i class="fa fa-plus-circle text-accent mr-2"></i> 添加新的模拟运行
        </h3>
        <button id="closeAddSimulationBtn" class="text-gray-400 hover:text-white transition-colors">
          <i class="fa fa-times"></i>
        </button>
      </div>
      <div class="p-4 overflow-y-auto flex-grow space-y-4">
        <div class="space-y-2">
          <label class="block text-sm text-gray-300">优化名称</label>
          <input type="text" id="optimizationName" 
            class="w-full bg-darker border border-dark-border rounded px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary/50">
        </div>



        <div class="space-y-2">
          <label class="block text-sm text-gray-300">总车辆数</label>
          <input type="number" id="totalVehicleCount" min="1" 
            class="w-full bg-darker border border-dark-border rounded px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary/50">
        </div>

        <div class="space-y-2">
          <label class="block text-sm text-gray-300">优化方法</label>
          <select id="optimizationMethod"
            class="w-full bg-darker border border-dark-border rounded px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary/50">
            <option value="HIERARCHICAL">分层优化</option>
            <option value="WEIGHTED">加权优化</option>
            <option value="GOAL_PROGRAMMING">目标规划</option>
          </select>
        </div>
        
        <!-- 优化权重配置 -->
        <div id="optimizationWeightsContainer" class="space-y-3">
          <div class="text-sm text-gray-400">
            <span id="weightDescription">请为以下指标配置权重：资源利用率、总成本、总时间、总距离、碳排放、满意度</span>
          </div>
          
          <!-- 分层优化权重配置 -->
          <div id="hierarchicalWeights" class="hidden space-y-2">
            <div class="text-xs text-gray-400 mb-2">
              说明：请为每个指标分配1-5的数字（数字越小越重要）
            </div>
            <div class="grid grid-cols-2 gap-4">
              <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-300 w-24">资源利用率：</span>
                <select class="hierarchical-weight bg-darker border border-dark-border rounded px-2 py-1 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary/50">
                  <option value="1">1 (最重要)</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
                  <option value="4">4</option>
                  <option value="5">5 (最不重要)</option>
                </select>
              </div>
              <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-300 w-24">总成本：</span>
                <select class="hierarchical-weight bg-darker border border-dark-border rounded px-2 py-1 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary/50">
                  <option value="1">1 (最重要)</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
                  <option value="4">4</option>
                  <option value="5">5 (最不重要)</option>
                </select>
              </div>
              <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-300 w-24">总时间：</span>
                <select class="hierarchical-weight bg-darker border border-dark-border rounded px-2 py-1 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary/50">
                  <option value="1">1 (最重要)</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
                  <option value="4">4</option>
                  <option value="5">5 (最不重要)</option>
                </select>
              </div>
              <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-300 w-24">总距离：</span>
                <select class="hierarchical-weight bg-darker border border-dark-border rounded px-2 py-1 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary/50">
                  <option value="1">1 (最重要)</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
                  <option value="4">4</option>
                  <option value="5">5 (最不重要)</option>
                </select>
              </div>
              <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-300 w-24">碳排放：</span>
                <select class="hierarchical-weight bg-darker border border-dark-border rounded px-2 py-1 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary/50">
                  <option value="1">1 (最重要)</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
                  <option value="4">4</option>
                  <option value="5">5 (最不重要)</option>
                </select>
              </div>
              <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-300 w-24">满意度：</span>
                <select class="hierarchical-weight bg-darker border border-dark-border rounded px-2 py-1 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary/50">
                  <option value="1">1 (最重要)</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
                  <option value="4">4</option>
                  <option value="5">5 (最不重要)</option>
                </select>
              </div>
            </div>
          </div>
          
          <!-- 加权优化权重配置 -->
          <div id="weightedWeights" class="space-y-2">
            <div class="text-xs text-gray-400 mb-2">
              说明：请为每个指标分配权重值，总和必须为100
            </div>
            <div class="grid grid-cols-2 gap-4">
              <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-300 w-24">资源利用率：</span>
                <input type="number" class="weighted-weight w-20 bg-darker border border-dark-border rounded px-2 py-1 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary/50" min="0" max="100">
                <span class="text-xs text-gray-400">%</span>
              </div>
              <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-300 w-24">总成本：</span>
                <input type="number" class="weighted-weight w-20 bg-darker border border-dark-border rounded px-2 py-1 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary/50" min="0" max="100">
                <span class="text-xs text-gray-400">%</span>
              </div>
              <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-300 w-24">总时间：</span>
                <input type="number" class="weighted-weight w-20 bg-darker border border-dark-border rounded px-2 py-1 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary/50" min="0" max="100">
                <span class="text-xs text-gray-400">%</span>
              </div>
              <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-300 w-24">总距离：</span>
                <input type="number" class="weighted-weight w-20 bg-darker border border-dark-border rounded px-2 py-1 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary/50" min="0" max="100">
                <span class="text-xs text-gray-400">%</span>
              </div>
              <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-300 w-24">碳排放：</span>
                <input type="number" class="weighted-weight w-20 bg-darker border border-dark-border rounded px-2 py-1 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary/50" min="0" max="100">
                <span class="text-xs text-gray-400">%</span>
              </div>
              <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-300 w-24">满意度：</span>
                <input type="number" class="weighted-weight w-20 bg-darker border border-dark-border rounded px-2 py-1 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary/50" min="0" max="100">
                <span class="text-xs text-gray-400">%</span>
              </div>
            </div>
            <div class="flex items-center justify-end text-sm text-gray-400">
              当前总和：<span id="weightedSum">0</span>%
            </div>
          </div>
          
          <!-- 目标规划权重配置 -->
          <div id="goalProgrammingWeights" class="hidden space-y-2">
            <div class="text-xs text-gray-400 mb-2">
              说明：请为每个指标分配目标值（0-100），默认为0
            </div>
            <div class="grid grid-cols-2 gap-4">
              <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-300 w-24">资源利用率：</span>
                <input type="number" class="goal-programming-weight w-20 bg-darker border border-dark-border rounded px-2 py-1 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary/50" min="0" max="100">
              </div>
              <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-300 w-24">总成本：</span>
                <input type="number" class="goal-programming-weight w-20 bg-darker border border-dark-border rounded px-2 py-1 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary/50" min="0" max="100">
              </div>
              <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-300 w-24">总时间：</span>
                <input type="number" class="goal-programming-weight w-20 bg-darker border border-dark-border rounded px-2 py-1 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary/50" min="0" max="100">
              </div>
              <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-300 w-24">总距离：</span>
                <input type="number" class="goal-programming-weight w-20 bg-darker border border-dark-border rounded px-2 py-1 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary/50" min="0" max="100">
              </div>
              <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-300 w-24">碳排放：</span>
                <input type="number" class="goal-programming-weight w-20 bg-darker border border-dark-border rounded px-2 py-1 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary/50" min="0" max="100">
              </div>
              <div class="flex items-center space-x-2">
                <span class="text-sm text-gray-300 w-24">满意度：</span>
                <input type="number" class="goal-programming-weight w-20 bg-darker border border-dark-border rounded px-2 py-1 text-white text-sm focus:outline-none focus:ring-2 focus:ring-primary/50" min="0" max="100">
              </div>
            </div>
          </div>
        </div>

        <div class="space-y-2">
          <label class="block text-sm text-gray-300">天气条件</label>
          <select id="weather"
            class="w-full bg-darker border border-dark-border rounded px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary/50">
            <option value="SUNNY">晴天</option>
            <option value="CLOUDY">多云</option>
            <option value="RAINY">雨天</option>
            <option value="SNOWY">雪天</option>
          </select>
        </div>

        <div class="space-y-2">
          <label class="block text-sm text-gray-300">车辆类型配置</label>
          <div id="vehicleTypesContainer" class="space-y-3">
            <div class="vehicle-type-item flex items-center space-x-2">
              <input type="text" placeholder="车辆类型名称"
                class="flex-grow bg-darker border border-dark-border rounded px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary/50">
              <input type="number" placeholder="数量" min="1"
                class="w-20 bg-darker border border-dark-border rounded px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary/50">
              <button class="remove-vehicle-type text-gray-400 hover:text-accent">
                <i class="fa fa-trash"></i>
              </button>
            </div>
          </div>
          <button id="addVehicleTypeBtn" class="text-primary text-sm hover:text-primary/80 transition-colors">
            <i class="fa fa-plus"></i> 添加车辆类型
          </button>
        </div>

        <div class="grid grid-cols-2 gap-4">
          <div class="space-y-2">
            <label class="block text-sm text-gray-300">供应链支持</label>
            <div class="flex items-center">
              <input type="checkbox" id="supplyChainSupport" class="mr-2">
              <span class="text-sm text-gray-400">启用</span>
            </div>
          </div>

          <div class="space-y-2">
            <label class="block text-sm text-gray-300">车辆休息配置</label>
            <div class="flex items-center">
              <input type="checkbox" id="vehicleRestEnabled" class="mr-2">
              <span class="text-sm text-gray-400">启用</span>
            </div>
          </div>
        </div>

        <div id="restDurationContainer" class="space-y-2 hidden">
          <label class="block text-sm text-gray-300">休息时长（小时）</label>
          <input type="number" id="restDurationHours" min="1" max="24"
            class="w-full bg-darker border border-dark-border rounded px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary/50">
        </div>

        <div class="grid grid-cols-2 gap-4">
          <div class="space-y-2">
            <label class="block text-sm text-gray-300">货物损耗率</label>
            <input type="number" id="cargoLossRate" min="0" max="1" step="0.001"
              class="w-full bg-darker border border-dark-border rounded px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary/50">
          </div>

          <div class="space-y-2">
            <label class="block text-sm text-gray-300">交通拥堵等级</label>
            <input type="number" id="trafficCongestionLevel" min="0" max="1" step="0.1"
              class="w-full bg-darker border border-dark-border rounded px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary/50">
          </div>
        </div>

        <div class="grid grid-cols-2 gap-4">
          <div class="space-y-2">
            <label class="block text-sm text-gray-300">车辆故障率</label>
            <input type="number" id="vehicleFailureRate" min="0" max="1" step="0.001"
              class="w-full bg-darker border border-dark-border rounded px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary/50">
          </div>

          <div class="space-y-2">
            <label class="block text-sm text-gray-300">时间步长（分钟）</label>
            <input type="number" id="timeStepMinutes" min="1"
              class="w-full bg-darker border border-dark-border rounded px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary/50">
          </div>
        </div>

        <div class="space-y-2">
          <label class="block text-sm text-gray-300">迭代次数</label>
          <input type="number" id="iterationCount" min="1"
            class="w-full bg-darker border border-dark-border rounded px-3 py-2 text-white focus:outline-none focus:ring-2 focus:ring-primary/50">
        </div>
      </div>
      <div class="p-4 border-t border-dark-border flex justify-between items-center">
        <div class="flex space-x-2">
          <button id="costPriorityBtn"
            class="bg-dark-border text-gray-300 px-3 py-1.5 rounded text-sm hover:bg-primary/20 hover:text-primary transition-colors">
            成本优先
          </button>
          <button id="efficiencyPriorityBtn"
            class="bg-dark-border text-gray-300 px-3 py-1.5 rounded text-sm hover:bg-primary/20 hover:text-primary transition-colors">
            效率优先
          </button>
          <button id="greenPriorityBtn"
            class="bg-dark-border text-gray-300 px-3 py-1.5 rounded text-sm hover:bg-primary/20 hover:text-primary transition-colors">
            环保优先
          </button>
        </div>
        <div class="flex space-x-3">
          <button id="cancelAddSimulationBtn"
            class="bg-darker text-gray-300 px-4 py-2 rounded hover:bg-dark-border transition-colors">
            取消
          </button>
          <button id="submitSimulationBtn"
            class="bg-accent text-white px-4 py-2 rounded hover:bg-accent/90 transition-colors">
            提交
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- 运行参数模态框 -->
  <div id="configurationModal"
    class="fixed inset-0 z-50 hidden items-center justify-center bg-black/70 backdrop-blur-sm">
    <div
      class="bg-dark-card border border-dark-border rounded-lg shadow-xl w-full max-w-2xl max-h-[80vh] flex flex-col">
      <div class="p-4 border-b border-dark-border flex justify-between items-center">
        <h3 class="text-lg font-semibold text-white flex items-center">
          <i class="fa fa-sliders text-primary mr-2"></i> 运行参数
        </h3>
        <button id="closeConfigurationBtn" class="text-gray-400 hover:text-white transition-colors">
          <i class="fa fa-times"></i>
        </button>
      </div>
      <div id="configurationData" class="p-4 overflow-y-auto flex-grow space-y-2">
        <!-- 配置数据将通过JavaScript动态生成 -->
        <div class="flex justify-center items-center h-40 text-gray-400">
          <span>加载中...</span>
        </div>
      </div>
      <div class="p-4 border-t border-dark-border flex justify-end">
        <button id="bottomCloseBtn"
          class="bg-primary text-white px-4 py-2 rounded hover:bg-primary/90 transition-colors">
          关闭
        </button>
      </div>
    </div>
  </div>
</body>

</html>